package utils;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import core.Codex;


public class FileIO
{
	public static Object readObject(String fileName)
			throws ClassNotFoundException, IOException
	{
		ObjectInputStream ois = null;
		Object inObj = new Object();
		try
		{
			File f = new File(fileName);
			if (f.length() > 0)
			{
				FileInputStream fis = new FileInputStream(fileName);
				ois = new ObjectInputStream(fis);

				inObj = ois.readObject();
			}
		}
		catch (FileNotFoundException ex)
		{
			throw new FileNotFoundException(ex.getMessage());
		}
		catch (StreamCorruptedException ex)
		{
			throw new StreamCorruptedException("Your trying to read "
					+ fileName + ", which is an empty file!");
		}
		catch (EOFException ex)
		{
			// Intentionally catch and do nothing
		}
		catch (ClassNotFoundException ex)
		{
			throw new ClassNotFoundException(ex.getMessage());
		}
		catch (IOException ex)
		{
			throw new IOException(ex.getMessage());
		}
		finally
		{
			if (ois != null)
			{
				try
				{
					ois.close();
				}
				catch (IOException ex)
				{
					throw new IOException(ex.getMessage());
				}
			}
		}

		return inObj;
	}

	public static void writeObject(Codex obj, String fileName)
			throws IOException, NotSerializableException
	{
		ObjectOutputStream objOut = null;
		try
		{
			FileOutputStream fos = new FileOutputStream(fileName);
			objOut = new ObjectOutputStream(fos);
			objOut.writeObject(obj);
		}
		catch (NotSerializableException ex)
		{
			throw new NotSerializableException(ex.getMessage());
		}
		catch (IOException ex)
		{
			throw new IOException(ex.getMessage());
		}
		finally
		{
			if (objOut != null)
			{
				try
				{
					objOut.close();
				}
				catch (IOException ex)
				{
					throw new IOException(ex.getMessage());
				}
			}
		}
	}

}
